<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use fast\Http;
use app\admin\model\Gpswarning as GpswarningModel;
use app\admin\model\Gpswarninglogs as GpswarninglogsModel;
use app\admin\model\cms\Archives;
use app\admin\model\cms\Channel;

/**
 * 车辆报警
 *
 * @icon fa fa-circle-o
 */
class Gpswarning extends Backend
{
    
    /**
     * Gpswarning模型对象
     * @var \app\admin\model\Gpswarning
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Gpswarning;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    
                    ->where($where)
                    ->order('gpstime', 'desc')
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','platenum','gpstime','longitude','latitude','tel_times','wechat_times','sms_times','address','alarminfo','createtime']);
                
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function sysn()
    {
        if ($this->request->isPost()) {
            $source = $this->request->post("source");
            if ($source) { 
                try { 
                    $sourceArr = explode(',', $source);
                    if($sourceArr){
                        foreach ($sourceArr as $key => $value) { 
                            if($value == 1){//同步光速报警
                                $this->sysnGsAlarm();
                            }
                        }
                    }
                    $this->success(); 
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        } 
    }
    //同步光速报警
    public function sysnGsAlarm(){
        $data = array();
        $data['Action'] = 'GetVehicleGpsInfo';
        $data['UserId'] = '光速监控';
        $data['Pwd'] = strtoupper(md5('gsjk123'));
        $data['Vehicles'] = '';
        $data['NeedAddress'] = '1';
        $json = json_encode($data); 
        $url = 'http://218.5.10.82:800/TopGps/Services/TopDataService.ashx?request='.$json; 
        $result = Http::sendRequest($url, array(), 'GET');
        $res = json_decode($result['msg'],true);
        $list = $res['Data'];
        if($list){
            foreach ($list as $key => $value) {
                if($value['AlarmInfo']){
                    $data = array();
                    $data['platenum'] = $value['PlateNum'];
                    $data['gpstime'] = strtotime($value['GpsTime']);
                    if(!GpswarningModel::where($data)->find()){
                        $data['longitude'] = $value['Longitude'];
                        $data['latitude'] = $value['Latitude'];
                        $data['address'] = $value['Address'];
                        $data['alarminfo'] = $value['AlarmInfo'];
                        $data['alarmcontent'] = json_encode($value);
                        $data['source'] = '光速监控';
                        $data['createtime']= time();
                        GpswarningModel::insert($data);
                    } 
                }
            }
        }  
    }
    /**
     * 拨打电话提醒
     */
    public function tel($ids)
    {
         if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $params['createtime'] = time();
                    $GpswarninglogsModel = new GpswarninglogsModel();

                    $id = $params['id'];
                    $row = $this->model->get(['id' => $id])->toArray(); 

                    unset($params['id']);  
                    $content = trim($params['sendMsg']);
                    $targetAddress = trim($params['targetAddress']);
                    if(!$targetAddress){
                        $this->error('手机号不能为空'); 
                    }
                    //拨打指定电话 
                    $url = "http://47.107.33.193:29003/api/ola/agents/1001/play_audio"; 
                    $dd = array();
                    $dd['numbers'] = $targetAddress;
                    $dd['batch_accept'] = '20190301';
                    $dd['filetype'] = 'text';
                    $dd['file'] = str_replace([")", "("], ',', $content);
                    $dd['gateway'] = '99999'; 
                    $rt = Http::sendRequest($url, $dd, 'PUT');
                    $rescontent = $rt['msg']; 
                    $d = json_decode($rescontent,true);
                    if($d['code'] == '200'){
                        $params['status'] = 1;
                    }
                    $params['rescontent'] = $rescontent;
                    $result = $GpswarninglogsModel->allowField(true)->save($params); 
                    if ($result !== false) {
                        //更新次数
                        $tel_times = $row['tel_times']+1;
                        GpswarningModel::where(['id'=>$id])->update(['tel_times'=>$tel_times]);
                     
                        $this->success('发送成功');
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $row = $this->model->get(['id' => $ids]);
        if (!$row)
            $this->error(__('No Results were found')); 
        $tuiRes = $this->getTuiList($row->platenum);
        if($tuiRes){
            $tel = $tuiRes->seotitle;
        }else{
            $tel = '';
        }

        $this->view->assign("tel", $tel);
        $this->view->assign("row", $row->toArray());
        return $this->view->fetch();
    }

    public function getTuiList($platenum){
        $tuiList = Archives::where(['title'=>$platenum])->find(); 
        if($tuiList){
            $res = Channel::where('id',$tuiList->channel_id)->find(); 
        }else{
            $res = null;
        }
        return $res;
    }
     /**
     * 拨打电话提醒
     */
    public function wechat($ids)
    {
         if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $params['createtime'] = time();
                    $GpswarninglogsModel = new GpswarninglogsModel();

                    $id = $params['id'];
                    $row = $this->model->get(['id' => $id])->toArray(); 

                    unset($params['id']);  
                    $content = trim($params['sendMsg']);
                    $targetAddress = trim($params['targetAddress']);

                    if(!$targetAddress){
                        $this->error('微信群组不能为空'); 
                    }
                    //拨打指定电话 
                    $url = "http://wx.350gps.cn/zt/api.php"; 
                    $dd = array();
                    $dd['to_wxid'] = $targetAddress;
                    $dd['msg'] = $content; 
                    $dd['act'] = 'send_msg';
                    $rt = Http::sendRequest($url, $dd, 'GET');
                    $rescontent = $rt['msg']; 
                    $d = json_decode($rescontent,true);
                    if($d['code'] == '0'){
                        $params['status'] = 1;
                    }
                    $params['rescontent'] = $rescontent;
                    $result = $GpswarninglogsModel->allowField(true)->save($params); 
                    if ($result !== false) {
                        //更新次数
                        $wechat_times = $row['wechat_times']+1;
                        GpswarningModel::where(['id'=>$id])->update(['wechat_times'=>$wechat_times]);
                     
                        $this->success('发送成功');
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $row = $this->model->get(['id' => $ids]);
        if (!$row)
            $this->error(__('No Results were found')); 
        $this->view->assign("row", $row->toArray());

        //拨打指定电话 
        $url = "http://wx.350gps.cn/zt/api.php"; 
        $dd = array(); 
        $dd['act'] = 'get_group_list';
        $tt = Http::sendRequest($url, $dd, 'GET'); 
        $this->view->assign("tt", json_decode($tt['msg'],true)); 
        return $this->view->fetch();
    }
}
